package com.ideaction.game.sec;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import com.ideaction.game.utils.SecStringUtil;

/**
 * 进入controller之前解析body
 * 
 * @author ZGame
 *
 */
@ControllerAdvice
public class SecRequestBodyAdvice implements RequestBodyAdvice {
	@Value("${security.open}")
	private boolean openSecurity;

	@Override
	public boolean supports(MethodParameter methodParameter, Type targetType,
			Class<? extends HttpMessageConverter<?>> converterType) {
		return openSecurity;
	}

	@Override
	public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
			Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
		try {
			return new MyHttpInputMessage(inputMessage);
		} catch (Exception e) {
			e.printStackTrace();
			return inputMessage;
		}
	}

	@Override
	public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
			Class<? extends HttpMessageConverter<?>> converterType) {
		return body;
	}

	@Override
	public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
			Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
		return body;
	}

	class MyHttpInputMessage implements HttpInputMessage {
		private HttpHeaders headers;
		private InputStream body;

		public MyHttpInputMessage(HttpInputMessage inputMessage) throws Exception {
			this.headers = inputMessage.getHeaders();
			this.body = SecStringUtil.parseSecStream(IOUtils.toString(inputMessage.getBody(), "UTF-8"));
//			this.body = IOUtils
//					.toInputStream(SecStringUtil.unSecString(IOUtils.toString(inputMessage.getBody(), "UTF-8")));
		}

		@Override
		public InputStream getBody() throws IOException {
			return body;
		}

		@Override
		public HttpHeaders getHeaders() {
			return headers;
		}

		/**
		 *
		 * @param requestData
		 * @return
		 */
		// public String easpString(String requestData) {
		// if (requestData != null && !requestData.equals("")) {
		// JSONObject jsonObj = JSONObject.parseObject(requestData);
		// if(!jsonObj.containsKey("RequestData")){
		// throw new AuthFailException();
		// }else{
		// return jsonObj.getString("RequestData");
		// }
		// }
		// return "";
		// }

	}
}
